Page({
  data: {
    loading: true,
    loadingMore: false,
    notifications: [],
    unreadCount: 0,
    currentPage: 1,
    pageSize: 10,
    hasMore: false
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '通知中心'
    })
    
    this.loadNotifications(true)
  },

  onShow() {
    // 页面显示时刷新通知
    this.loadNotifications(true)
  },

  // 加载通知列表
  async loadNotifications(reset = false) {
    if (reset) {
      this.setData({
        loading: true,
        notifications: [],
        currentPage: 1,
        hasMore: false
      })
    }

    try {
      const result = await wx.cloud.callFunction({
        name: 'getUserNotifications',
        data: {
          page: reset ? 1 : this.data.currentPage,
          pageSize: this.data.pageSize,
          markAsRead: false // 不自动标记为已读
        }
      })

      if (result.result && result.result.success) {
        const { notifications, pagination, unreadCount } = result.result.data
        
        // 处理通知数据
        const processedNotifications = notifications.map(notification => ({
          ...notification,
          createTimeText: this.formatTime(notification.createTime),
          typeText: this.getTypeText(notification.type),
          data: {
            ...notification.data,
            auditTimeText: notification.data.auditTime ? this.formatTime(notification.data.auditTime) : ''
          }
        }))

        this.setData({
          notifications: reset ? processedNotifications : [...this.data.notifications, ...processedNotifications],
          currentPage: pagination.page,
          hasMore: pagination.hasMore,
          unreadCount: unreadCount
        })

        console.log(`✅ 加载了 ${processedNotifications.length} 条通知，未读 ${unreadCount} 条`)
      } else {
        throw new Error(result.result?.error || '加载失败')
      }

    } catch (error) {
      console.error('❌ 加载通知失败:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ 
        loading: false,
        loadingMore: false
      })
    }
  },

  // 加载更多通知
  async loadMoreNotifications() {
    if (this.data.loadingMore || !this.data.hasMore) return

    this.setData({ 
      loadingMore: true,
      currentPage: this.data.currentPage + 1
    })

    await this.loadNotifications(false)
  },

  // 标记单条通知为已读
  async markAsRead(e) {
    const notificationId = e.currentTarget.dataset.id
    
    try {
      // 这里可以调用专门的标记已读云函数
      // 暂时通过重新加载来更新状态
      const notifications = this.data.notifications.map(notification => {
        if (notification._id === notificationId) {
          return { ...notification, isRead: true, readTime: new Date() }
        }
        return notification
      })

      this.setData({
        notifications: notifications,
        unreadCount: Math.max(0, this.data.unreadCount - 1)
      })

      wx.showToast({
        title: '已标记为已读',
        icon: 'success'
      })

    } catch (error) {
      console.error('❌ 标记已读失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 全部标记为已读
  async markAllAsRead() {
    try {
      await wx.cloud.callFunction({
        name: 'getUserNotifications',
        data: {
          page: 1,
          pageSize: 100, // 获取更多通知来标记
          markAsRead: true
        }
      })

      // 刷新通知列表
      this.loadNotifications(true)

      wx.showToast({
        title: '全部已标记为已读',
        icon: 'success'
      })

    } catch (error) {
      console.error('❌ 全部标记已读失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 查看注册状态
  viewRegistrationStatus() {
    wx.navigateTo({
      url: '/pages/registration-status/registration-status'
    })
  },

  // 修改注册信息
  modifyRegistration(e) {
    const teamId = e.currentTarget.dataset.teamId
    
    wx.showModal({
      title: '修改注册信息',
      content: '确定要修改注册信息吗？修改后将重新提交审核。',
      confirmText: '确定',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 跳转到注册状态页面，由那里处理修改逻辑
          wx.navigateTo({
            url: '/pages/registration-status/registration-status'
          })
        }
      }
    })
  },

  // 查看施工队伍列表
  viewTeamList() {
    wx.switchTab({
      url: '/pages/construction-team/construction-team'
    })
  },

  // 格式化时间
  formatTime(time) {
    if (!time) return ''
    
    const date = new Date(time)
    const now = new Date()
    const diff = now - date

    // 小于1分钟
    if (diff < 60000) {
      return '刚刚'
    }

    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    }

    // 小于1天
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    }

    // 小于7天
    if (diff < 604800000) {
      return `${Math.floor(diff / 86400000)}天前`
    }

    // 超过7天显示具体日期
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

  // 获取通知类型文本
  getTypeText(type) {
    const typeMap = {
      'audit_result': '审核结果',
      'resubmit_registration': '重新提交',
      'system_notice': '系统通知',
      'order_notice': '订单通知'
    }
    return typeMap[type] || '通知'
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadNotifications(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  }
})
